<?php
class XA_User {

	public $id = null;
	protected $user_data;
	protected $session;



	public function __construct() {
		$this->session =& $_SESSION[get_class($this)];
		$this->id =& $this->session['id'];
	}



	public function login ($id) {
		$this->id = $id;
	}



	// nazwa dwuznaczna (authorization?), używać authen
	public function auth ($login, $password) {
		return $this->authen($login, $password);
	}



	public function authen ($login, $password) {
		$result = xa::query("
			SELECT 
				user_id 
			FROM 
				user 
			WHERE
				active = 1
				AND 
				login = '".xa_db::esc($login)."' 
				AND 
				password = '".md5($password)."'
		");

		return intval($result->val());
	}



	public function fb_authen (&$input) {
		// jeśli przyszło bez hasza w GET to przekierowujemy na url GET z haszem wziętym z location.hash (po #), żeby jakos przekazać hasha
		if (empty($input['hash'])) {
			?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
			<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
					<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
				</head>
				<body>
					<script type="text/javascript">
						window.location = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search + "&hash=1&" + window.location.hash.substring(1);
					</script>
				</body>
			</html>
			<?php
			die();
		}

		// pobieramy fb uid
		$fb_user = json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$input['access_token']), true);

		if ($user_data = xa::table('user')->find(array('fb_id' => $fb_user['id']))) {
			return $user_data['user_id'];
		} else {
			// jak jeszcze nie mamy takiego fb uid to dodajemy usera
			return xa::table('user')->insert(array('fb_id' => $fb_user['id'], 'email' => $fb_user['email']));
		}

		return false;
	}



	public function get ($field = null) {
		if ($this->id) {
			if (!$this->user_data) {
				$this->user_data = xa::query("SELECT * FROM ".TP."user WHERE user_id = ".$this->id." LIMIT 1")->row();
			}

			unset($this->user_data['password']);

			if ($field) {
				return (isset($this->user_data[$field]) ? $this->user_data[$field] : null);
			} else {
				return $this->user_data;
			}
		}

		return false;
	}



	public function logout () {
		$this->session = array();
	}
}
